<?php
/**
 * Create by PhpStorm
 * User: lijia
 * Data: 2020/8/10
 * Time: 10:52
 */

namespace app\api\business;


use app\api\controller\UserCommon;
use app\api\model\ShopCar;
use think\Exception;
use think\facade\Db;
use think\facade\Request;

class ShopCarBus extends UserCommon
{

    public $model;
    public $url;
    public function __construct()
    {
        parent::__construct();
        $this->url = Request::scheme() . '://' . Request::host();
        $this->model = new ShopCar();
    }

    /**
     * 添加到购物车
     * @param $data
     * @return int|string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add($data)
    {
        $param = [
            'user_id' => $this->user_id,
            'goods_id' => $data['goods_id'],
            'share_num' => $data['share_num']
        ];
        $checkCard = $this->model->where('user_id', $this->user_id)->where('goods_id', $data['goods_id'])->find();
        if ($checkCard) {
            throw new Exception('该商品已在你的购物车中', 0);
        }
        return $this->model->insertGetId($param);
    }


    public function getList($where)
    {
        $list = Db::name('shop_car')->alias('a')
            ->join('goods b', 'b.id = a.goods_id', 'left')
            ->where($where)
            ->field('a.*,b.title,b.cover,b.deposit_price,b.origin_price,b.present_price,a.share_num,b.stock,b.store_address,b.store_mobile')
            ->select()->toArray();
        foreach ($list as $k => $v) {
            $list[$k]['cover'] = $this->url . $v['cover'];
        }
        return $list;
    }

    /**
     * 删除购物车商品
     */
    public function del($ids)
    {
        return $this->model->whereIn('id', $ids)->delete();
    }

    /**
     * 修改购物车商品数量
     * @param $id
     * @param $share_num
     * @return bool
     */
    public function edit($id, $share_num)
    {
        // 修改购物车数量
        return $this->model->where('id', $id)->save(['share_num' => $share_num]);
    }

    /**
     * 下单
     * @param $ids
     * @param $address_id
     * @param $sur_num
     * @param $remarks
     * @return bool
     * @throws Exception
     */
    public function placeOrder($ids, $address_id, $sur_num, $remarks)
    {
        Db::startTrans();
        try {
            $shopCar = Db::name('shop_car')->alias('a')
                ->join('goods b', 'b.id = a.goods_id', 'left')
                ->whereIn('a.id', $ids)
                ->field('a.*,b.share,b.price,b.stock,b.title')
                ->select()->toArray();
            if (!$shopCar) {
                throw new Exception('不存在购物车数据', 0);
            }
            $total_price = 0; // 订单总价
            $total_num = 0; // 下单商品总个数
            foreach ($shopCar as $k => $v) {
                //总价 = 商品单价 * 下单份数
                $total_price = $total_price + ($v['share_num'] * $v['price']); // 总价
                $total_num = $total_num + ($v['share_num'] * $v['share']); // 下单所有商品总数
                // 查看商品库存
                if ($v['stock'] < $v['share_num']) {
                    throw new Exception($v['title'] . ' 库存不足', 0);
                }
                /**
                 * 客户要求在添加购物车时加减库存
                 * // 减库存
                 * Db::name('goods')->where('id',$v['goods_id'])->dec('stock',$v['share_num'])->update();
                 * // 如果库存为0；则自动下架该商品
                 * if (Db::name('goods')->where('id',$v['goods_id'])->lock(true)->value('stock') == 0){
                 * Db::name('goods')->where('id',$v['goods_id'])->update(['status' => 2]);
                 * }
                 **/
            }
            // 下单数与用户余库比较 填写的余库数量加上购买数量不能大于店铺库存上限
            $max_stock_number = Db::name('user')->where('user_id',$this->user_id)->value('max_stock_number');
            if ($max_stock_number < ($sur_num * $total_num)) {
                throw new Exception('已超余库上限', 0);
            }
            // 插入订单表数据
            $orderData = [
                'order_sn' => date('Ymd') . time() . random_int(1000, 9999),
                'user_id' => $this->user_id,
                'address_id' => $address_id,
                'total_price' => $total_price,
                'remarks' => $remarks,
                'create_time' => date('Y-m-d H:i:s')
            ];
            $order_id = Db::name('orders')->insertGetId($orderData);
            // 讲订单详情插入订单商品表
            $goodsOrderData = [];
            foreach ($shopCar as $k => $v) {
                $goodsOrderData[] = [
                    'order_id' => $order_id,
                    'goods_id' => $v['goods_id'],
                    'goods_share_num' => $v['share_num']
                ];
            }
            Db::name('orders_goods')->insertAll($goodsOrderData);
            // 删除下单成功的购物车数据
            Db::name('shop_car')->whereIn('id', $ids)->delete();
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage(), 0);
        }
    }
}